package utils

import (
	"net"

	"github.com/pkg/errors"
)

// ErrIPNotObtained IP地址未获取到
var ErrIPNotObtained = errors.New("IP not obtained")

// GetLocalIP 获取本机IP地址
func GetLocalIP() (string, error) {
	ss, err := net.InterfaceAddrs()
	if err != nil {
		return "", errors.WithStack(err)
	}

	for _, v := range ss {
		if n, ok := v.(*net.IPNet); ok && !n.IP.IsLoopback() {
			if n.IP.To4() != nil {
				return n.IP.String(), nil
			}
		}
	}

	return "", errors.WithStack(ErrIPNotObtained)
}
